import datetime
import json
import re
import time

from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection

from ihome.utils.fastdfs.fastdfs_storage import FastDFSStorage
from ihome.utils.views import housecount, LoginRequiredMixin
from wangziye.models import House, Order


class AddOrder(View, LoginRequiredMixin):
    def post(self, request):
        json_dict = json.loads(request.body)
        house_id = json_dict.get('house_id')
        str_start_date = json_dict.get('start_date')
        str_end_date = json_dict.get('end_date')
        # '检查全部参数'
        if not all([house_id, str_start_date, str_end_date]):
            return JsonResponse({
                'errno': '4002',
                "errmsg": '缺少必传参数'
            })
        # 单个检查
        try:
            house = House.objects.get(id=house_id)
        except Exception as e:
            return JsonResponse({
                'errno': '4001',
                "errmsg": '数据库查询错误'
            })

        try:
            # 字符串转化为时间类型
            start_date = datetime.datetime.strptime(str_start_date, '%Y-%m-%d').date()
            end_date = datetime.datetime.strptime(str_end_date, '%Y-%m-%d').date()
        except Exception as e:
            return JsonResponse({
                'errno': '4103',
                "errmsg": '参数错误'
            })
        # 检验当前时间和起始时间和结束时间的顺序
        now_time = datetime.date.today()
        if not ((now_time <= start_date) and (start_date < end_date)):
            return JsonResponse({
                'errno': '4004',
                "errmsg": '数据错误'})
        # 获取用户自己的房屋
        try:
            houses = House.objects.filter(user=request.user)
        except Exception as e:
            return JsonResponse({
                'errno': '4001',
                "errmsg": '数据库查询错误'
            })
        # 判断是否为自己发布的房屋详情页
        if house in houses:
            return JsonResponse({
                'errno': '4004',
                "errmsg": '数据错误'
            })
        # 获取时间段内房屋的已住房间数
        maxnum = housecount(house, start_date, end_date)
        # 判断已租出去的房间数是否大于等于房间总数
        if maxnum >= house.room_count:
            return JsonResponse({'errno': '4003',
                                 'errmsg': '该时段房间已满'})
        redis_conn = get_redis_connection('order')
        date = start_date

        while date < end_date:
            # 获取每日的房屋已租出去的房间数
            num = redis_conn.hget('order_%s' % house_id, str(date))
            # 如果为空，则已租出房间数为0
            if not num:
                num = 0
            # 否则转化为int类型
            else:
                num = int(num.decode())
            num += 1
            # 存储到hash里
            redis_conn.hset('order_%s'% house_id, str(date), num)
            # 日期加一天
            date += datetime.timedelta(days=1)
        # 获取租的天数
        day = end_date - start_date
        order = Order.objects.create(user=request.user,
                                     house=house,
                                     begin_date=start_date,
                                     end_date=end_date,
                                     days=day.days,
                                     house_price=house.price*100,
                                     amount=day.days * house.price)

        return JsonResponse({
            'data': {"order_id": order.id},
            'errno': '0',
            "errmsg": '下单成功'})


    def get(self, request):
        role = request.GET.get('role')
        user = request.user
        # 检查必传的参数
        if not role:
            return JsonResponse({
                'errno': '4002',
                "errmsg": '缺少必传参数'
            })
        # 获取图片
        fsdf = FastDFSStorage()
        # 如果是房客
        if role == 'custom':
            try:
                # 获取房客的所有订单
                custom_orders = Order.objects.filter(user=user)
            except Exception as e:
                return JsonResponse({
                    'errno': '4001',
                    "errmsg": '数据库查询错误'})
            # 列表推导式
            orders = [{"amount": order.house_price,
                        "comment": order.comment,
                        "ctime": order.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                        "days": order.days,
                        "end_date": order.end_date,
                        "img_url": fsdf.url(str(order.house.index_image_url)),
                        "order_id": order.id,
                        "start_date": order.begin_date,
                        "status": order.ORDER_STATUS_ENUM[order.status],
                        "title": order.house.title} for order in custom_orders]
        # 如果是房东
        else:
            try:
                # 获取房东所有的房屋
                landlord_houses = House.objects.filter(user=user)
            except Exception as e:
                return JsonResponse({
                    'errno': '4001',
                    "errmsg": '数据库查询错误'})
            # 遍历房东所有房屋获取每一个房屋
            for landlord_house in landlord_houses:
                # 获取每一个房屋的所有订单
                landlord_orders = Order.objects.filter(house=landlord_house)
                # 列表推导式
                orders = [{"amount": order.house_price,
                            "comment": order.comment,
                            "ctime": order.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                            "days": order.days,
                            "end_date": order.end_date,
                            "img_url": fsdf.url(str(order.house.index_image_url)),
                            "order_id": order.id,
                            "start_date": order.begin_date,
                            "status": order.ORDER_STATUS_ENUM[order.status],
                            "title": order.house.title} for order in landlord_orders]
        return JsonResponse({
            'data': {'orders': orders},
            "errmsg": "OK",
            "errno": "0"})


class OrderStatus(View, LoginRequiredMixin):
    def put(self, request, order_id):
        json_dict = json.loads(request.body)
        action = json_dict.get('action')
        reason = json_dict.get('reason')
        user = request.user
        if action not in ('accept', 'reject'):
            return JsonResponse({
                'errno': '4002',
                "errmsg": '缺少必传参数'})
        try:
            order = Order.objects.get(id=order_id)
        except Exception as e:
            return JsonResponse({
                'errno': '4001',
                "errmsg": '数据库查询错误'})
        # 如果接单
        if action == 'accept':
            # 订单状态改为待评价
            order.status = 3
            house = order.house
            # 房屋订单数加一
            while True:
                # 乐观锁
                origin_order_count = house.order_count
                new_order_count = origin_order_count + 1
                result = House.objects.filter(id=house.id,
                                              order_count=origin_order_count).update(order_count=new_order_count)
                if result == '0':
                    continue
                try:
                    house.save()
                except Exception as e:
                    return JsonResponse({
                        'errno': '4004',
                        "errmsg": '数据库存储错误'})
                break
        # 如果拒绝
        else:
            order.status = 6
            order.comment = reason
        try:
            order.save()
        except Exception as e:
            return JsonResponse({
                'errno': '4004',
                "errmsg": '数据库存储错误'})
        return JsonResponse({
                    "errno": "0",
                    "errmsg": "操作成功"
                    })














